﻿using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LittleBee.CellStore
{
	class CodeGenerator
	{
		public CodeGenerator()
		{
			//准备一个代码编译器单元
			_unit = new CodeCompileUnit();

			//准备必要的命名空间（这个是指要生成的类的空间）
			//var sampleNamespace = new CodeNamespace(Namespace);

			//把该命名空间加入到编译器单元的命名空间集合中
			//_unit.Namespaces.Add(sampleNamespace);

		}

		protected CodeCompileUnit _unit;
		//FileStream _tmpCodeFile;
		//StringWriter _swCode;

		public int AddNamespace(string nameSpace)
		{
			return _unit.Namespaces.Add(new CodeNamespace(nameSpace));
		}

		//private List<string> _lstImportedNamespace = new List<string>();
		public void AddImportedNamespace(string strNamespace, int nIndex = 0)
		{
			_unit.Namespaces[nIndex].Imports.Add(new CodeNamespaceImport(strNamespace));
		}

		//private List<CodeTypeDeclaration> _lstCodeTypeDeclaration = new List<CodeTypeDeclaration>();
		public void AddCodeTypeDeclaration(CodeTypeDeclaration codeTypeDeclaration, int nIndex = 0)
		{
			_unit.Namespaces[nIndex].Types.Add(codeTypeDeclaration);
		}

		public virtual string GeneratedCode()
		{
			CodeGeneratorOptions options;
			options = new CodeGeneratorOptions
			{
				BracingStyle = "C",
				BlankLinesBetweenMembers = true
			};

			//_tmpCodeFile = File.Open(Path.GetTempFileName(), FileMode.Create);
			//using (System.IO.StreamWriter sw = new System.IO.StreamWriter(_tmpCodeFile))
			StringWriter sw = new StringWriter();
			{
				CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
				provider.GenerateCodeFromCompileUnit(_unit, sw, options);
			}

			//_tmpCodeFile.Seek(0, SeekOrigin.Begin);
			//return File.ReadAllText(_tmpCodeFile.Name);
			return sw.ToString();


		}
	}
}
